import 'package:star_author/utils/common_util/shared_preferences/sp_util.dart';

mixin ControllerPersist {
  late String _key;

  init(String key) {
    this._key = key;
  }

  Map<String, dynamic> get(String key) {
    dynamic d = SpUtil.getDynamic('${_key}_${key}');
    if (d is String) {
      return {};
    }
    Map<String, dynamic>? obj =
        SpUtil.getDynamic('${_key}_${key}') as Map<String, dynamic>?;
    return obj ?? {};
  }

  List<Map<dynamic, dynamic>> getList(String key) {
    List<Map<dynamic, dynamic>>? list = SpUtil.getObjectList('${_key}_${key}');
    return list ?? [];
  }

  save(key, obj) {
    String k = '${_key}_$key';
    if (_checkList(obj)) {
      obj = SpUtil.putObjectList(k, obj);
    } else {
      obj = SpUtil.putObject(k, obj);
    }
  }

  clear(String key) {
    SpUtil.remove('${_key}_${key}');
  }

  clearAll() {
    SpUtil.clear();
  }

  saveList(Map map) {
    map.entries.forEach((entry) {
      String key = '${_key}_${entry.key}';
      if (_checkList(entry.value)) {
        SpUtil.putObjectList(key, entry.value);
      } else {
        SpUtil.putObject(key, entry.value ?? "");
      }
    });
  }

  bool _checkList(obj) {
    RegExp reg = new RegExp(r'List<.*?>');
    if (obj == null) return false;
    return reg.allMatches(obj.runtimeType.toString()).length > 0;
  }
}
